import { login } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'

const getDefaultState = () => {
  return {
    token: getToken(),
    userInfo: {}
  }
}

const state = getDefaultState()

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
    setToken(token)
  },
  SET_INfO(state, payload) {
    state.userInfo = payload
  },
  // user logout
  logout(state) {
    removeToken()
    state.token = null
  }
}

const actions = {
  // user login
  async login({ commit }, userInfo) {
    const res = await login(userInfo)
    commit('SET_TOKEN', res.token)
    commit('SET_INfO', res)
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

